//
//  TTRecyclingListOneViewCell.m
//  TaoTuo
//
//  Created by LG on 2020/8/28.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTRecyclingListOneViewCell.h"
#import "LLDateUtilis.h"
#import <UIButton+WebCache.h>

@interface TTRecyclingListOneViewCell ()

@property (nonatomic, strong) UIImageView *pictureView;
@property (nonatomic, strong) UILabel *gujiaLabel;
@property (nonatomic, strong) UILabel *moneyLabel;

/// 估价中的cell下面一行显示
@property (nonatomic, strong) UIButton *infoBtn;

/// 待寄送的cell下面一行显示
@property (nonatomic, strong) YYLabel *commentsLabel;

/// 待检测的cell下面一行显示
@property (nonatomic, strong) UIView *oneBgView;
@property (nonatomic, strong) UIButton *tagBtn;
@property (nonatomic, strong) UILabel *infoLabel;

@property (nonatomic, strong) TTRecyclingGujiaModel *model;
@property (nonatomic, assign) RecyclingListOneCellType cellType;

@end

@implementation TTRecyclingListOneViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setupSubviews];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyAction) name:@"recyclingOneCellTimerNotify_key" object:nil];
        
        
    }
    return self;
}

- (void)notifyAction
{
    if (self.cellType == GuJiaZhong && self.model.Progress == 2) {
        
        NSString *text = [NSString stringWithFormat:@"已等待：%02ld:%02ld:%02ld", self.model.hour, self.model.minute, self.model.second];
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
        [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(DF2121) range:[attr.string rangeOfAll]];
        [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(333333) range:[text rangeOfString:@"已等待："]];
        [self.infoBtn setAttributedTitle:attr forState:UIControlStateNormal];
    }
}

- (void)setModel:(TTRecyclingGujiaModel *)model cellType:(RecyclingListOneCellType)cellType
{
    self.model = model;
    self.cellType = cellType;
    if (model.Picture.length > 0) {
        [self.pictureView sd_setImageWithURL:[NSURL URLWithString:model.Picture] placeholderImage:[UIImage imageNamed:@"f_placeholder_img"] options:SDWebImageRetryFailed];
    }
    
    if ([model.Price intValue] > 0) {
        NSString *str = [NSString stringWithFormat:@"￥%@", model.Price];
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
        [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:9] range:NSMakeRange(0, 1)];
        self.moneyLabel.attributedText = attrStr;
    } else {
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"—"];
        [attrStr addAttribute:NSForegroundColorAttributeName value:UIColorHex(333333) range:[attrStr.string rangeOfAll]];
        [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:[attrStr.string rangeOfAll]];
        self.moneyLabel.attributedText = attrStr;
    }
    
    if (cellType == GuJiaZhong) {
        
        self.infoBtn.hidden = NO;
        self.commentsLabel.hidden = YES;
        self.oneBgView.hidden = YES;

        if (model.Progress == 3) {
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"需要进一步完善信息"];
            [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(DF2121) range:[attr.string rangeOfAll]];
            [self.infoBtn setImage:[UIImage imageNamed:@"hintgantanhao"] forState:UIControlStateNormal];
            [self.infoBtn setAttributedTitle:attr forState:UIControlStateNormal];
        } else if (model.Progress == 2) {
            // 计时，计算时间差
            // 获取当前时间
            [self.infoBtn setImage:[UIImage imageNamed:@"naozhong"] forState:UIControlStateNormal];
//            NSString *currentDateStr = [LLDateUtilis getCurrentTimeString];
//            NSDateComponents *diff = [LLDateUtilis compareFromDateString:self.model.TriggerArtificialPriceTime toDateString:currentDateStr deteUnit:Hour | Minute | Second];
//            [self handleTimeEventWithComponents:diff];
            [self notifyAction];
        } else {
            [self.infoBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            [self.infoBtn setAttributedTitle:[[NSAttributedString alloc] init] forState:UIControlStateNormal];
        }
        
    } else if (cellType == DaiJiSong) {
        
        self.infoBtn.hidden = YES;
        self.commentsLabel.hidden = NO;
        self.oneBgView.hidden = YES;
        
        if (model.Information_Record.Information_Record_EvaluationComment.length > 0) {
            NSString *str = [NSString stringWithFormat:@" 评语 %@", model.Information_Record.Information_Record_EvaluationComment];
            YYTextBorder *border = [YYTextBorder borderWithFillColor:UIColorHex(#DED1FE) cornerRadius:2];
            border.insets = UIEdgeInsetsMake(-2, -3, -2, -3);
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
            NSRange range = [attrStr.string rangeOfString:@" 评语"];
            [attrStr setFont:[UIFont systemFontOfSize:8] range:range];
            [attrStr setColor:UIColorHex(#8452FF) range:range];
            [attrStr setTextBackgroundBorder:border range:range];
            self.commentsLabel.attributedText = attrStr;
        } else {
            self.commentsLabel.attributedText = [[NSMutableAttributedString alloc] initWithString:@" "];
        }

        
    } else {
        
        self.infoBtn.hidden = YES;
        self.commentsLabel.hidden = YES;
        self.oneBgView.hidden = NO;
        
        UIImage *img = [[UIImage imageNamed:@"上门取货_mini"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.tagBtn setImage:img forState:UIControlStateNormal];
        [self.tagBtn setTitleColor:UIColorHex(B79BFB) forState:UIControlStateNormal];
        self.tagBtn.layer.borderColor = UIColorHex(#B79BFB).CGColor;
        if (model.Progress == 5) {
            int method = model.SendingInformation.SendMethod.intValue;
            if (method == 1) {
                @weakify(self)
                [self.tagBtn setImageWithURL:[NSURL URLWithString:model.SendingInformation.ICON] forState:UIControlStateNormal placeholder:nil options:YYWebImageOptionRefreshImageCache completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                    @strongify(self)
                    image = [image imageByResizeToSize:CGSizeMake(13, 13)];
                    UIImage *nImg = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                    [self.tagBtn setImage:nImg forState:UIControlStateNormal];

                }];
                NSString *title = [NSString stringWithFormat:@" %@", model.SendingInformation.Express];
                [self.tagBtn setTitle:title forState:UIControlStateNormal];
                [self.tagBtn setTitleColor:UIColorHex(333333) forState:UIControlStateNormal];
                self.tagBtn.layer.borderColor = UIColor.whiteColor.CGColor;
                self.infoLabel.text = [NSString stringWithFormat:@"单号:%@", model.SendingInformation.ExpressNumber];
            } else if (method == 2) {
                [self.tagBtn setTitle:@" 上门取货" forState:UIControlStateNormal];
                self.infoLabel.text = [NSString stringWithFormat:@"上门时间:%@", model.SendingInformation.VisitingTime];
            } else if (method == 3) {
                [self.tagBtn setTitle:@" 到店交易" forState:UIControlStateNormal];
                self.infoLabel.text = [NSString stringWithFormat:@"到店时间:%@", model.SendingInformation.ArrivalTime];
            } else if (method == 4) {
                [self.tagBtn setTitle:@" 免寄上架" forState:UIControlStateNormal];
                self.infoLabel.text = model.SendingInformation.SendStatus_Text;
            } else {
                [self.tagBtn setTitle:@"" forState:UIControlStateNormal];
                self.infoLabel.text = @"";
            }
        }
        
    }
}
//
//- (void)handleTimeEventWithComponents:(NSDateComponents *)diff
//{
//    self.model.hour = diff.hour >= 0 ? diff.hour : 0;
//    self.model.minute = diff.minute >= 0 ? diff.minute : 0;
//    self.model.second = diff.second >= 0 ? diff.second : 0;
//    // 总秒数
//    self.model.totalSecond = self.model.hour * 3600 + self.model.minute * 60 + self.model.second;
//
//    NSString *text = [NSString stringWithFormat:@"已等待：%02ld:%02ld:%02ld", self.model.hour, self.model.minute, self.model.second];
//    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
//    [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(DF2121) range:[attr.string rangeOfAll]];
//    [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(333333) range:[text rangeOfString:@"已等待："]];
//    [self.infoBtn setAttributedTitle:attr forState:UIControlStateNormal];
////    if (self.model.timer == nil) {
//        YYWeakProxy *proxy = [YYWeakProxy proxyWithTarget:self];
//        self.model.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:proxy selector:@selector(timerAction) userInfo:nil repeats:YES];
//        [[NSRunLoop currentRunLoop] addTimer:self.model.timer forMode:NSRunLoopCommonModes];
////    }
//
//}
//
//- (void)timerAction
//{
//    self.model.totalSecond++;
//
//    self.model.hour = self.model.totalSecond / 3600;
//    self.model.minute = self.model.totalSecond % 3600 / 60;
//    self.model.second = self.model.totalSecond % 3600 % 60;
//
//    NSString *text = [NSString stringWithFormat:@"已等待：%02ld:%02ld:%02ld", self.model.hour, self.model.minute, self.model.second];
//    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
//    [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(DF2121) range:[attr.string rangeOfAll]];
//    [attr addAttribute:NSForegroundColorAttributeName value:UIColorHex(333333) range:[text rangeOfString:@"已等待："]];
//    [self.infoBtn setAttributedTitle:attr forState:UIControlStateNormal];
//
//}

///// 重用之前清楚计时器
//- (void)prepareForReuse
//{
//    [super prepareForReuse];
//    // 先清除定时器
////    [self.model.timer invalidate];
////    self.model.timer = nil;
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupSubviews
{
    _pictureView = [[UIImageView alloc] init];
    _pictureView.layer.cornerRadius = 8;
    _pictureView.layer.masksToBounds = YES;
//    _pictureView.contentMode = UIViewContentModeScaleAspectFill;
    [self.contentView addSubview:_pictureView];
    [self.pictureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(8);
        make.bottom.equalTo(self.contentView).mas_offset(-9);
        make.width.height.mas_equalTo(84);
    }];
    
    _gujiaLabel = [UILabel labelWithTitle:@"估价金额" color:UIColorHex(333333) font:[UIFont boldSystemFontOfSize:14]];
    [self.contentView addSubview:_gujiaLabel];
    [_gujiaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.left.equalTo(self.pictureView.mas_right).mas_offset(90);
    }];
    
    _moneyLabel = [UILabel labelWithTitle:@"—" color:UIColorHex(DF2121) font:[UIFont boldSystemFontOfSize:18]];
    [self.contentView addSubview:_moneyLabel];
    [_moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.gujiaLabel.mas_bottom).mas_offset(3);
        make.centerX.equalTo(self.gujiaLabel);
    }];
    
    /// 待寄送的cell下面一行显示
    [self setupDaiJiSong];
    
    /// 待检测的cell下面一行显示
    [self setupDaiJianCe];
    
    /// 估价中的cell下面一行显示
    [self setupGuJiaZhong];
    
    
}


- (void)setupGuJiaZhong
{
    _infoBtn = [UIButton createButtonWithTitle:@"" titleColor:UIColorHex(DF2121) titleFont:[UIFont systemFontOfSize:13] backgroundColor:nil target:nil action:nil];
    [_infoBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [self.contentView addSubview:_infoBtn];
    [_infoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.contentView).mas_offset(-6);
        make.centerX.equalTo(self.gujiaLabel);
//        make.left.greaterThanOrEqualTo(self.pictureView.mas_right).mas_offset(10);
    }];
    
}

- (void)setupDaiJiSong
{
    _commentsLabel = [[YYLabel alloc] init];
    _commentsLabel.font = [UIFont systemFontOfSize:11];
    _commentsLabel.numberOfLines = 2;
    _commentsLabel.textVerticalAlignment = YYTextVerticalAlignmentBottom;
    [self.contentView addSubview:_commentsLabel];
    [_commentsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.pictureView.mas_right).mas_offset(10);
        make.bottom.equalTo(self.contentView).mas_offset(-5);
        make.right.equalTo(self.contentView.mas_right).mas_offset(-10);
        make.height.mas_equalTo(40);
    }];
    
}

- (void)setupDaiJianCe
{
    _oneBgView = [[UIView alloc] init];
    [self.contentView addSubview:_oneBgView];
    [_oneBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.contentView).mas_offset(-8);
        make.left.equalTo(self.pictureView.mas_right).mas_offset(10);
        make.right.equalTo(self.contentView.mas_right).mas_offset(8);
        make.height.mas_equalTo(26);
    }];
    
    _tagBtn = [UIButton createButtonWithTitle:@"上门取货" titleColor:UIColorHex(#8553FF) titleFontSize:11 borderColor:UIColorHex(#B79BFB) cornerRadius:3 contentEdgeInsets:UIEdgeInsetsZero target:nil action:nil];
    [_tagBtn setImage:[UIImage imageNamed:@"上门取货_mini"] forState:UIControlStateNormal];
    [_oneBgView addSubview:_tagBtn];
    [_tagBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.centerY.equalTo(self.oneBgView);
        make.height.mas_equalTo(18);
        make.width.mas_equalTo(70);
    }];
    
    _infoLabel = [UILabel labelWithTitle:@"上门时间：1314" color:UIColorHex(333333) font:[UIFont boldSystemFontOfSize:12]];
    [self.oneBgView addSubview:_infoLabel];
    [_infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.gujiaLabel);
        make.centerY.equalTo(self.oneBgView);
    }];
}


- (void)setFrame:(CGRect)frame
{
    frame.origin.x += 10;
    frame.size.width -= 20;
    frame.origin.y += 10;
    frame.size.height -= 10;
    
    [super setFrame:frame];
    
}

@end
